package me.illtamer.infinite.hook.realize;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.exception.InitializationException;
import me.illtamer.infinite.hook.TranslatorAdaptor;
import me.illtamer.infinite.pojo.Global;
import me.illtamer.infinite.util.SecurityUtil;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Connection;

import java.io.IOException;

/**
 * 百度翻译
 * */
@Slf4j
public class BaiDuTranslator implements TranslatorAdaptor {

    public static final String TRANSLATE_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private boolean init = false;
    private Connection connection;
    private String appId;
    private String appKey;
    private int maxLength = -1;

    /**
     * 翻译方法
     * @param src  原始字段
     * @param from 原始语言
     * @param to   目标语言
     */
    @Override
    @NotNull
    public String translate(@NotNull String src, @NotNull String from, @NotNull String to) throws IOException {
        if (src.length() == 0) return src;

        log.debug("Request Url: " + TRANSLATE_URL);

        String salt = SecurityUtil.salt(11);

        String request = appId + src + salt + appKey;
        log.debug("原签名: " + request);
        String sign = SecurityUtil.md5(request);
        log.debug("Sign: " + sign);

        return connection.url(TRANSLATE_URL)
                    .data("from", from)
                    .data("to", to)
                    .data("q", src)
                    .data("salt", salt)
                    .data("sign", sign)
                    .post().body().text();
    }

    @Override
    public boolean init(@NotNull Global global, ConfigurationSection apiSection) {
        if (init)
            log.warn("{} is already init ! Please check your code if you are not reload the config !", this.getClass().getName());
        ConfigurationSection section = apiSection.getConfigurationSection("baidu");
        if (section == null)
            throw new InitializationException("Can not find the configuration section: ", this);
        this.appId = section.getString("app-id");
        this.appKey = section.getString("app-key");
        this.maxLength = section.getInt("max-length");
        if (appId == null || appKey == null || maxLength == -1)
            throw new InitializationException("Missing configuration !", this);

        this.connection = global
                .createConnection(TRANSLATE_URL)
                .data("appid", appId);
        return (init = true);
    }

    /**
     * 一次翻译所支持的最大字符长度
     * @apiNote urlEncode下
     */
    @Override
    public int getMaxLength() {
        return maxLength;
    }

}
